package com.storeroompda.base.views;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.storeroompda.R;
import com.storeroompda.base.model.Model;
import com.storeroompda.base.mvp.BaseMvp;
import com.storeroompda.base.present.BasePresenter;
import com.storeroompda.dialogs.WaitDialog;
import com.storeroompda.scanf.BroadcastConfig;
import com.storeroompda.tool.ToastUtils;
import com.storeroompda.utils.ColorUtil;
import com.storeroompda.utils.DateUtil;
import com.storeroompda.utils.SpringScaleInterpolator;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Date;

public abstract class BaseActivity<M extends Model, V extends BaseView, P extends BasePresenter> extends Activity implements BaseMvp<M, V, P>,  BaseView{

    protected DateUtil dateUtilInstance;
    protected ColorUtil colorUtilInstance;
    protected String tag = "BaseActivity";
    protected WaitDialog waitDialog;
    protected P presenter;

    protected BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(BroadcastConfig.CUSTOM_NAME))
            {
                onScanf(intent.getStringExtra("scannerdata"));
            }
        }
    };

    protected void onScanf(String code)
    {

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        initialization();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            //透明状态栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        }
        waitDialog = new WaitDialog(this, R.style.Dialog1);
        WindowManager.LayoutParams lp = waitDialog.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;

        //创建
        presenter = createPresenter();
        if (presenter != null) {
            //将Model层注册到Presenter中
            presenter.registerModel(createModel());
             //将View层注册到Presenter中
            presenter.registerView(createView());
        }
        EventBus.getDefault().register(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastConfig.CUSTOM_NAME);
        registerReceiver(mBroadcastReceiver, intentFilter);
        }

        @Override
        protected void onDestroy () {
            super.onDestroy();
            dateUtilInstance = null;
            colorUtilInstance = null;
            presenter.destroy();
            EventBus.getDefault().unregister(this);
            unregisterReceiver(mBroadcastReceiver);
            //unBind.unbind();
        }

    protected void initialization() {
        dateUtilInstance = DateUtil.getDateUtilInstance();
        colorUtilInstance = ColorUtil.getColorUtilInstance();
    }


    protected void intentToActivityWithoutParameter(Activity context, Class clazz) {
        Intent intent = new Intent();
        intent.setClass(context, clazz);
        startActivity(intent);
    }

    protected void setTitleBarMargin(RelativeLayout relativeLayout){
        FrameLayout.LayoutParams rl_universal_normal_header_Params = (FrameLayout.LayoutParams) relativeLayout.getLayoutParams();
        rl_universal_normal_header_Params.height = rl_universal_normal_header_Params.height + getStatusHeight(this);
        relativeLayout.setLayoutParams(rl_universal_normal_header_Params);
    }

    protected void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }


    protected void onScaleAnimationBySpringWayOne(ImageView imageView) {
        ObjectAnimator animatorX = ObjectAnimator.ofFloat(imageView, "scaleX", 0.8f, 1.0f);
        ObjectAnimator animatorY = ObjectAnimator.ofFloat(imageView, "scaleY", 0.8f, 1.0f);
        AnimatorSet set = new AnimatorSet();
        set.setDuration(1300);
        set.setInterpolator(new SpringScaleInterpolator(0.4f));
        set.playTogether(animatorX, animatorY);
        set.start();

    }


    /**
     * 获得通知栏的高度
     * @return
     */
    protected static int getStatusHeight(Context context){
        int resid = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if(resid > 0){
            return context.getResources().getDimensionPixelSize(resid);
        }
        return -1;
    }



    /**
     * 单独设置EditTextHint字体大小
     * */

    protected void setHintTextSize(String text,EditText editText){
        SpannableString ss = new SpannableString(text);//定义hint的值
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(16,true);//设置字体大小 true表示单位是sp
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        editText.setHint(new SpannedString(ss));
    }

    protected void initBroadcastReciever() {
        // 发送广播到扫描工具内的应用设置项
        Intent intent = new Intent(BroadcastConfig.BROADCAST_SETTING);
        // 修改扫描工具内应用设置中的开发者项下的广播名称
        intent.putExtra(BroadcastConfig.BROADCAST_KEY, BroadcastConfig.CUSTOM_NAME);
//        intent.putExtra(BroadcastConfig.SEND_KEY, "BROADCAST");
//        intent.putExtra(BroadcastConfig.END_KEY, "NONE");
        intent.putExtra(BroadcastConfig.VIBERATE_KEY, false);
        intent.putExtra(BroadcastConfig.SOUND_KEY, true);
        intent.putExtra(BroadcastConfig.CONTINIU_KEY, false);
//        intent.putExtra("interval", 1000);
        sendBroadcast(intent);
    }

    protected void chooseDate(final TextView view)
    {
        DatePickDialog dialog = new DatePickDialog(this);
        //设置上下年分限制
        dialog.setYearLimt(8);
        //设置标题
        dialog.setTitle("选择日期");
        //设置类型
        dialog.setType(DateType.TYPE_YMD);
        //设置消息体的显示格式，日期格式
        dialog.setMessageFormat("yyyy-MM-dd");
        //设置选择回调
        dialog.setOnChangeLisener(null);
        //设置点击确定按钮回调
        dialog.setOnSureLisener(new OnSureLisener() {
            @Override
            public void onSure(Date date) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                view.setText(sdf.format(date));
            }
        });
        dialog.show();
    }

    @Override
    public void showProgress() {
        waitDialog.show();
    }

    @Override
    public void hideProgress() {
        waitDialog.dismiss();
    }

    @Override
    public void showMsg(String msg)
    {
        ToastUtils.showSingleToast(this,msg);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onBaseMessageEvent(Object o) {
    }




}
